﻿using System;
using System.Collections.Generic;
using System.Text;

namespace GameSeed.Communication.Client
{
    class CommandManager
    {
        private object syncObject = new object();

        public event CommandHandler UnkownCommandHandler;

        private Dictionary<string, CommandItem> list = new Dictionary<string, CommandItem>();

        public void RegistCommand(string command, CommandHandler handler)
        {
            lock (syncObject)
            {
                if (list.ContainsKey(command))
                {
                    CommandItem item = list[command];
                    item.StringHandler += handler;
                }
                else
                {
                    CommandItem item = new CommandItem();
                    item.Command = command;
                    item.StringHandler += handler;

                    list.Add(command, item);
                }
            }
        }

        public void ClearCommand(string command)
        {
            lock (syncObject)
            {
                if (list.ContainsKey(command))
                {
                    list.Remove(command);
                }
            }
        }

        public void Excute(string text)
        {
            var result = text.IndexOf(' ');
            if (result != -1)
            {
                var command = text.Substring(0, result);
                var data = text.Substring(result + 1, text.Length - result - 1);

                excuteCommand(command, data);
            }
            else
            {
                if (UnkownCommandHandler != null)
                    UnkownCommandHandler("", text);
            }

        }

        private void excuteCommand(string command, string data)
        {
            lock (syncObject)
            {
                if (list.ContainsKey(command))
                {
                    var item = list[command];
                    item.Excute(command, data);
                }
                else
                {
                    if (UnkownCommandHandler != null)
                        UnkownCommandHandler(command , data);
                }
            }
        }
    }
}
